package io.renren.modules.app.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.snapshot.SnapshotRequest;
import com.qcloud.cos.model.ciModel.snapshot.SnapshotResponse;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.io.InputStream;
import java.util.List;


/**
 * @ClassName CosUtil.java
 * @description: 腾讯云对象存储工具类
 * @author: huangjiaxin
 * @create: 2021-03-02 09:56
 **/
public class CosUtil {
    public static void main(String[] args) {
        //COSClient cosClient = GetClient();
        //CreateBucket("hjx-test","1259615938");
        //deleteCosVideoObject("冷狗.mp4" );
        //getObjectList(CosConstant.ObjectKey_Image_Prefix);
        PutObjectResult putObjectResult = putCosImageObject("C:\\Users\\Administrator\\Desktop\\啊.jpg");
        String requestId1 = putObjectResult.getRequestId();
        String versionId1 = putObjectResult.getVersionId();
        System.out.println(requestId1);
        System.out.println(versionId1);
        ObjectMetadata metadata = putObjectResult.getMetadata();
        String requestId = metadata.getRequestId();
        String versionId = metadata.getVersionId();
        System.out.println(requestId);
        System.out.println(versionId);

    }


    //创建Cos客户端
    public static COSClient getClient(){
        // 初始化用户身份信息（secretId, secretKey）。
        String secretId = CosConstant.SecretId;
        String secretKey = CosConstant.SecretKey;
        COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
        //设置地域
        String regionName = CosConstant.RegionName_gz;
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        //创建cos客户端
        COSClient cosClient = new COSClient(cred,clientConfig);
        //返回客户端
        return cosClient;
    }

    //创建Bucket
    public static Bucket createBucket(String prefixBucket,String appId){
        String bucketName = prefixBucket + "-" + appId; //存储桶名称，格式：BucketName-APPID
        System.out.println(bucketName);
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置 bucket 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.Private);

        Bucket bucketResult = null;
        try{
            bucketResult = getClient().createBucket(createBucketRequest);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
        return bucketResult;
    }

    //创建Bucket
    public static Bucket createBucket(String prefixBucket){
        return createBucket(prefixBucket,CosConstant.AppId);
    }


    //上传视频对象
    public static PutObjectResult putCosVideoObject(String filePath){
        String ObjectKeyPrefix = CosConstant.ObjectKey_Video_Prefix;
        return putCosObject(filePath,ObjectKeyPrefix);
    }

    //上传视频对象
    public static PutObjectResult putCosVideoObject(File file){
        String ObjectKeyPrefix = CosConstant.ObjectKey_Video_Prefix;
        return putCosObject(file,ObjectKeyPrefix);
    }

    //上传图片对象
    public static PutObjectResult putCosImageObject(String filePath){
        String ObjectKeyPrefix = CosConstant.ObjectKey_Image_Prefix;
        return putCosObject(filePath,ObjectKeyPrefix);
    }

    //上传图片对象
    public static PutObjectResult putCosImageObject(File file){
        String ObjectKeyPrefix = CosConstant.ObjectKey_Image_Prefix;
        return putCosObject(file,ObjectKeyPrefix);
    }


    //上传对象,文件路径
    public static PutObjectResult putCosObject(String filePath,String ObjectKeyPrefix){
        //指定要上传的文件
        File file = new File(filePath);
        return putCosObject(file,ObjectKeyPrefix);
    }


    //上传对象,文件
    public static PutObjectResult putCosObject(File file,String ObjectKeyPrefix){
        //获取文件名
        String fileName = file.getName();
        //System.out.println(fileName);
        // 指定要上传到的存储桶
        String bucketName = CosConstant.BucketName;
        // 指定要上传到 COS 上对象键，比如 video/1.mp4 就会创建一个video目录文件，1.mp4放在video目录下
        String key = ObjectKeyPrefix + "/" + fileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        PutObjectResult putObjectResult = getClient().putObject(putObjectRequest);
        return putObjectResult;
    }


    /**
     * @description 通过流的形式上传视频文件
     * @param inputStream
     * @param fileName
     * @param contentLength
     * @param contentType
     * @return
     */
    public static PutObjectResult putCosVideoObject(InputStream inputStream , String fileName,Long contentLength ,String contentType) throws CosClientException, CosServiceException{
        String ObjectKeyPrefix = CosConstant.ObjectKey_Video_Prefix;
        return putCosObject(inputStream,ObjectKeyPrefix,fileName,contentLength,contentType);
    }

    /**
     * @description 通过流的形式上传图片文件
     * @param inputStream
     * @param fileName
     * @param contentLength
     * @param contentType
     * @return
     */
    public static PutObjectResult putCosImageObject(InputStream inputStream , String fileName,Long contentLength ,String contentType){
        String ObjectKeyPrefix = CosConstant.ObjectKey_Image_Prefix;
        return putCosObject(inputStream,ObjectKeyPrefix,fileName,contentLength,contentType);
    }


    /**
     * @description 通过流上传文件到COS
     * @param inputStream       输入流
     * @param ObjectKeyPrefix   对象key前缀
     * @param fileName      文件
     * @param contentLength 流的长度
     * @param contentType   文件内容类型
     * @return
     */
    public static PutObjectResult putCosObject(InputStream inputStream,String ObjectKeyPrefix,String fileName,Long contentLength , String contentType){
        // 指定要上传到的存储桶
        String bucketName = CosConstant.BucketName;
        // 指定要上传到 COS 上对象键，比如 video/1.mp4 就会创建一个video目录文件，1.mp4放在video目录下
        String key = ObjectKeyPrefix + "/" + fileName;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度
        objectMetadata.setContentLength(contentLength);
        // 设置 Content type, 默认是 application/octet-stream
        objectMetadata.setContentType(contentType);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream,objectMetadata);
        PutObjectResult putObjectResult = getClient().putObject(putObjectRequest);
        return putObjectResult;
    }




    //删除视频对象
    public static void deleteCosVideoObject(String videoObjectSuffix){
        String bucketName = CosConstant.BucketName;
        String objectKey = CosConstant.ObjectKey_Video_Prefix + "/" + videoObjectSuffix;
        deleteCosObject(objectKey);
    }
    //删除图片对象
    public static void deleteCosImageObject(String imageObjectSuffix){
        String bucketName = CosConstant.BucketName;
        String objectKey = CosConstant.ObjectKey_Image_Prefix + "/" + imageObjectSuffix;
        deleteCosObject(objectKey);
    }
    //删除对象
    public static void deleteCosObject(String objectKey){
        String bucketName = CosConstant.BucketName;
        getClient().deleteObject(bucketName, objectKey);
    }



    //获取对象List 没想用，没完善
    public static void getObjectList(String objectPrefix){
        String bucketName = CosConstant.BucketName;
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        // 设置bucket名称
        listObjectsRequest.setBucketName(bucketName);
        // prefix表示列出的object的key以prefix开始
        listObjectsRequest.setPrefix(objectPrefix + "");
        // deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
        listObjectsRequest.setDelimiter("");
        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
        listObjectsRequest.setMaxKeys(1000);
        ObjectListing objectListing = null;

        do {
            try {
                objectListing = getClient().listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
                return;
            } catch (CosClientException e) {
                e.printStackTrace();
                return;
            }
            // commonprefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
            List<String> commonPrefixs = objectListing.getCommonPrefixes();
            System.out.println(commonPrefixs);
            // object summary表示所有列出的object列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                // 文件的路径key
                String key = cosObjectSummary.getKey();
                // 文件的etag
                String etag = cosObjectSummary.getETag();
                // 文件的长度
                long fileSize = cosObjectSummary.getSize();
                // 文件的存储类型
                String storageClasses = cosObjectSummary.getStorageClass();

                System.out.println(key);
                System.out.println(etag);
                System.out.println(fileSize);
                System.out.println(storageClasses);
            }
            String nextMarker = objectListing.getNextMarker();
            System.out.println(nextMarker);
            listObjectsRequest.setMarker(nextMarker);
        } while (objectListing.isTruncated());
        
    }
    
    /**
     * @description 数据万象截图，桶必须开通该功能才能使用。
     * @param videoName cos上video文件夹下的视频名字 1.mp4
     * @param imageName 输出到cos上image文件夹下的图片名字 1.jpg
     */
    public static SnapshotResponse getSnapshotPic(String videoName,String imageName){
        SnapshotRequest request = new SnapshotRequest();
        //2.添加请求参数 参数详情请见api接口文档
        request.setBucketName(CosConstant.BucketName);
        String inputPath = CosConstant.ObjectKey_Video_Prefix + "/" + videoName;
        request.getInput().setObject(inputPath);
        request.getOutput().setBucket(CosConstant.BucketName);
        request.getOutput().setRegion(CosConstant.RegionName_gz);
        String outputPath = CosConstant.ObjectKey_Image_Prefix + "/" + imageName;
        //example:image/1.jpg
        request.getOutput().setObject(outputPath);
        request.setTime("2");
        //3.调用接口,获取截图响应对象
        SnapshotResponse response = getClient().generateSnapshot(request);
        return response;
    }





}
